package net.folab.fo.codegen;

import java.util.HashMap;
import java.util.Map;

public class ByteArrayClassLoader extends ClassLoader {

    private final Map<String, byte[]> bytecodes;

    private final Map<String, Class<?>> classes;

    public ByteArrayClassLoader() {
        bytecodes = new HashMap<String, byte[]>();
        classes = new HashMap<String, Class<?>>();
    }

    public void define(String name, byte[] bs) {
        if (bytecodes.containsKey(name))
            throw new RuntimeException();
        bytecodes.put(name, bs);
    }

    @Override
    protected Class<?> findClass(String name)
            throws ClassNotFoundException {
        if (bytecodes.containsKey(name)) {
            if (classes.containsKey(name))
                return classes.get(name);
            byte[] bs = bytecodes.get(name);
            Class<?> klass = defineClass(name, bs, 0, bs.length);
            classes.put(name, klass);
            return klass;
        } else {
            throw new ClassNotFoundException(name);
        }
    }

}
